﻿using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using Labthink.PCSoft.UniversalHost4.Instrument.Model;
using Labthink.PCSoft.UniversalHost4.Instrument.MyControls;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Model.Query;
using Labthink.PCSoft.UniversalHost4.UserControls;
using Labthink.PCSoft.UniversalHost4.UserControls.MsgBox;
using Labthink.PCSoft.UniversalHost4.Utility;
using Newtonsoft.Json;

namespace Labthink.PCSoft.UniversalHost4.Instrument.Forms
{
    public partial class FrmSchemeList
    {
        private QueryScheme _query;
        private ObservableCollection<ParamScheme> _schemes;
        private int _pageCount;
        private NotifyManager _notify;
        public ParamScheme LoadedScheme { get; set; }
        public int OpenFrom { get; set; }
        private bool _isFirst = true;

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetCursorPos(out POINT pt);
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode)]
        private static extern IntPtr FindWindow(string className, string windowName);

        public FrmSchemeList()
        {
            InitializeComponent();
            if (!Debugger.IsAttached)
            {
                WindowState = WindowState.Maximized;
            }
            else
            {
                WindowState = WindowState.Normal;

                double height = SystemParameters.FullPrimaryScreenHeight;
                double width = SystemParameters.FullPrimaryScreenWidth;

                Width = 1024;
                Height = 768;

                Top = (height - Height) / 2;
                Left = (width - Width) / 2;
            }
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void UcSearchBox_OnOnSearch(object sender, SearchEventArgs e)
        {
            _query.Name = e.SearchText;
            _query.PageIndex = 1;
            _schemes.Clear();

            //Schemes.SetValue(HeightProperty, 500.0);
            _getData();
        }

        private void CloseBtn_TouchUp(object sender, TouchEventArgs e)
        {
            Close();
        }

        private void FrmSchemeList_OnLoaded(object sender, RoutedEventArgs e)
        {
            _notify = NotifyManager.InstanceManager(this);

            IntPtr a = new WindowInteropHelper(this).Handle;
            int temp = Win32Api.GetWindowLong(a, -20);
            Win32Api.SetWindowLong(a, -20, temp | 0x08000000);
            var hwndSource = HwndSource.FromHwnd(a);
            hwndSource?.AddHook(WndProc);

            _query = new QueryScheme { PageCount = 20, PageIndex = 1 };
            if (Common.BaseInfo.Gmp && Common.Permissions.All(p => p.Code != "190100".Clear()))
            {
                _query.TestType = Common.CurrentStandard;
            }

            _schemes = new ObservableCollection<ParamScheme>();
            Schemes.ItemsSource = _schemes;
            _getData();
        }

        private void _getData()
        {
            BorderNext.Visibility = Visibility.Collapsed;
            Loading.Visibility = Visibility.Visible;
            //var sd = await Common.Instrument.Commands.GetParamSchemesAsync(_query);
            //if (string.IsNullOrEmpty(sd.Value) || sd.Value == "null")
            //{
            //    Loading.Visibility = Visibility.Collapsed;
            //    return;
            //}
            //var pds = JsonConvert.DeserializeObject<PagedList<ParamScheme>>(sd.Value);
            //if (!pds.InnerList.Any())
            //{
            //    Loading.Visibility = Visibility.Collapsed;
            //    return;
            //}
            BorderNext.Visibility = Visibility.Visible;
            //_pageCount = pds.PageCount;
            //_schemes.AddRange(pds.InnerList);
            //Schemes.SetValue(HeightProperty, (_schemes.Count+1) * 40.0);

            _pageCount = 0;
            Loading.Visibility = Visibility.Collapsed;
        }

        private async void _loadScheme(int id)
        {
            Loading.Visibility = Visibility.Visible;
            var r = await Common.Instrument.Commands.GetParamSchemeByIdAsync(id);
            Loading.Visibility = Visibility.Collapsed;
            if (r.ErrorCode >= 0)
            {
                LoadedScheme = JsonConvert.DeserializeObject<ParamScheme>(r.Value);
                Common.CurrentParamProject = JsonConvert.DeserializeObject<ParamProject>(LoadedScheme.Scheme, new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All
                });
                Common.CurrentStandard = LoadedScheme.TestType;
                Common.CurrentParamProject.Id = LoadedScheme.Id;
                Common.CurrentParamProject.IsDefault = LoadedScheme.IsDefault;
                Common.CurrentParamProject.TestType = LoadedScheme.TestType;
                Common.CurrentParamProject.TestTypeName = LoadedScheme.TestTypeName;
                Common.CurrentParamProject.Name = LoadedScheme.SchemeName;
                //Common.CurrentStandard = Common.CurrentParamProject.DefaultParam.Standard;
                //返回参数设置
                DialogResult = true;
                Close();
                return;
            }

            MessageBox.Show(r.ErrorMsg);
        }

        private async void Default_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;
            Loading.Visibility = Visibility.Visible;
            var r = await Common.Instrument.Commands.SetDefaultSchemeAsync(btn.Tag.ToInt());
            if (r.ErrorCode >= 0)
            {
                _notify.ShowSuccess(r.ErrorMsg);
                _query.PageIndex = 1;
                _schemes.Clear();
                _getData();
            }
            else
            {
                _notify.ShowError(r.ErrorMsg);
            }
            Loading.Visibility = Visibility.Collapsed;
        }

        private async void Delete_OnClick(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            var btn = sender as Button;
            if (btn == null) return;
            //if (MessageBox.Show(Resources.GetLanguageValue("SureToDelete"), "", MessageBoxButton.OKCancel, MessageBoxImage.Warning,
            //        MessageBoxResult.OK) == MessageBoxResult.OK)
            if (MyMessageBox.Show(this, LanguageManager.GetLanguageValue("SureToDelete"), "", MyMessageBoxButton.OkCancel, MyMessageBoxImage.Warning,
                   MyMessageBoxDefaultButton.Ok) == MyMessageBoxResult.Ok)
            {
                Loading.Visibility = Visibility.Visible;
                var r = await Common.Instrument.Commands.DeleteParamSchemeById(btn.Tag.ToInt());
                
                if (r.ErrorCode >= 0)
                {
                    _notify.ShowSuccess(r.ErrorMsg);
                    _query.PageIndex = 1;
                    _schemes.Clear();
                    _getData();
                    if (Common.CurrentParamProject.Name == btn.CommandParameter.ToString())
                    {
                        Common.CurrentParamProject.Name = "";
                    }
                }
                else
                {
                    _notify.ShowError(r.ErrorMsg);
                }
                Loading.Visibility = Visibility.Collapsed;
            }
        }

        private void Load_OnClick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            if (btn == null) return;
            _loadScheme(btn.Tag.ToInt());
        }

        private void Schemes_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (Common.Permissions.All(p => p.Code != "SchemeModifly".Clear()))
            {
                return;
            }
            var ti = Schemes.SelectedItem as ParamScheme;
            if (ti == null) return;
            _loadScheme(ti.Id);
        }

        private void UIElement_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //throw new NotImplementedException();
            _next();
        }

        private void UIElement_OnTouchDown(object sender, TouchEventArgs e)
        {
            // throw new NotImplementedException();
            _next();
        }

        private void _next()
        {
            if (_query.PageIndex == _pageCount) return;
            _query.PageIndex++;
            _getData();
        }

        private void FButtonAdd_OnClick(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            var frm = new FrmParamSet();
            frm.ShowDialog(this);
            _query.PageIndex = 1;
            _schemes.Clear();

            //Schemes.SetValue(HeightProperty, 500.0);
            _getData();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //if (e.LeftButton == MouseButtonState.Pressed)
            //    DragMove();
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == 0x0216)
            {
                System.Drawing.Rectangle rect = (System.Drawing.Rectangle)Marshal.PtrToStructure(lParam, typeof(System.Drawing.Rectangle));
                Left = rect.Left;
                Top = rect.Top;
            }

            /*
             WM_ACTIVATE =$0006;一个窗口被激活或失去激活状态；
             WM_SETFOCUS =$0007;获得焦点后
             WM_KILLFOCUS =$0008;失去焦点

             WM_SETCURSOR =$0020;如果鼠标引起光标在某个窗口中移动且鼠标输入没有被捕获时，就发消息给某个窗口
             WM_MOUSEACTIVATE =$0021;当光标在某个非激活的窗口中而用户正按着鼠标的某个键发送此消息给当前窗口
             WM_CHILDACTIVATE =$0022;发送此消息给MDI子窗口当用户点击此窗口的标题栏，或当窗口被激活，移动，改变大小

             */


            //if (msg == 0x0020)
            //{
            //    this.Opacity = 0;
            //}
            //if (msg == 0x0201)//0201
            //{
            //    IntPtr hWnd = GetForegroundWindow();
            //    uint processId;
            //    uint threadid = GetWindowThreadProcessId(hWnd, out processId);
            //    GUITHREADINFO lpgui = new GUITHREADINFO();
            //    lpgui.cbSize = Marshal.SizeOf(lpgui);

            //    if (GetGUIThreadInfo(threadid, ref lpgui))
            //    {
            //        if (lpgui.hwndCaret != 0)
            //        {
            //      this.Opacity = 1;
            //this.WindowState = WindowState.Normal;
            //}
            //else
            //{
            //    //       this.Opacity = 0;
            // this.WindowState = WindowState.Minimized;
            //        }

            //    }
            //}
            //if(msg==0x)


            return IntPtr.Zero;
        }

        private void Txt_OnGotFocus(object sender, RoutedEventArgs e)
        {
            if (_isFirst)
            {
                _isFirst = false;
                return;
            }
        }

        private void Txt_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (_isOpen()) return;
            if (sender is FrameworkElement fe)
            {
            }
        }

        private void Txt_PreviewTouchDown(object sender, System.Windows.Input.TouchEventArgs e)
        {
            if (_isOpen()) return;
            if (sender is FrameworkElement fe)
            {
              
            }
        }

        private bool _isOpen()
        {
            return true;
        }

        public void Connect(int connectionId, object target)
        {
        }
    }
}
